package com.jinzhuo.music.controller;

import com.alibaba.fastjson.JSONObject;
import com.jinzhuo.music.domain.Consumer;
import com.jinzhuo.music.service.ConsumerService;
import com.jinzhuo.music.utils.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {
    @Autowired
    private ConsumerService consumerService;

    /**
     * 添加用户
     */
    @RequestMapping(value = "addConsumer",method = RequestMethod.POST)
    public Object addConsumer(HttpServletRequest request){
        JSONObject object = new JSONObject();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        String sex = request.getParameter("sex").trim();
        String phoneNum = request.getParameter("phoneNum").trim();
        String email = request.getParameter("email").trim();
        String birth = request.getParameter("birth").trim();
        String introduction = request.getParameter("introduction").trim();
        String location = request.getParameter("location").trim();
        String avator = request.getParameter("avator").trim();
//        判断用户名和密码是否为空
        if (username==null||"".equals(username)){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"用户名不能为空");
            return object;
        }
//        判断用户名是否存在
        Consumer name = consumerService.queryConsumerByName(username);
        if (name!=null){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"用户名已存在");
            return object;
        }
        if (password==null||"".equals(password)){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"密码不能为空");
            return object;
        }
        //把生日转换成data形式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
             date = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //保存到用户的对象中
        Consumer consumer = new Consumer();
        consumer.setUsername(username);
        consumer.setPassword(password);
        consumer.setSex(new Byte(sex));
        consumer.setPhoneNum(phoneNum);
        consumer.setEmail(email);
        consumer.setBirth(date);
        consumer.setIntroduction(introduction);
        consumer.setLocation(location);
        consumer.setAvator(avator);
        boolean flag = consumerService.addConsumer(consumer);
        if (flag){
            object.put(Consts.CODE,"1");
            object.put(Consts.MSG,"添加成功");
        }else {
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"添加失败");
        }
        return object;
    }

    /**
     * 登录用户
     */
    @RequestMapping(value = "loginComsumer",method = RequestMethod.POST)
    public Object loginComsumer(HttpServletRequest request){
        JSONObject object = new JSONObject();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();

//        判断用户名和密码是否存在
        if (username==null||"".equals(username)){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"用户名不能为空");
            return object;
        }
        if (password==null||"".equals(password)){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"密码不能为空");
            return object;
        }
        //保存到用户的对象中
        Consumer consumer = new Consumer();
        consumer.setUsername(username);
        consumer.setPassword(password);
        boolean flag = consumerService.verifyPassword(username,password);
        if (flag){
            object.put(Consts.CODE,"1");
            object.put(Consts.MSG,"登录成功");
            object.put("userMsg",consumerService.queryConsumerByName(username));
        }else {
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"登录失败，用户名或密码出错了");
        }
        return object;
    }

    /**
     * 修改用户
     */
    @RequestMapping(value = "updateConsumer",method = RequestMethod.POST)
    public Object updateConsumer(HttpServletRequest request){
        JSONObject object = new JSONObject();
        String id = request.getParameter("id").trim();
        String username = request.getParameter("username").trim();
        String password = request.getParameter("password").trim();
        String sex = request.getParameter("sex").trim();
        String phoneNum = request.getParameter("phoneNum").trim();
        String email = request.getParameter("email").trim();
        String birth = request.getParameter("birth").trim();
        String introduction = request.getParameter("introduction").trim();
        String location = request.getParameter("location").trim();
//        String avator = request.getParameter("avator").trim();
        if (username==null||"".equals(username)){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"用户名不能为空");
            return object;
        }
        if (password==null||"".equals(password)){
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"密码不能为空");
            return object;
        }
        //把生日转换成data形式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        try {
            date = dateFormat.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //保存到用户的对象中
        Consumer consumer = new Consumer();
        consumer.setId(Integer.parseInt(id));
        consumer.setUsername(username);
        consumer.setPassword(password);
        consumer.setSex(new Byte(sex));
        consumer.setPhoneNum(phoneNum);
        consumer.setEmail(email);
        consumer.setBirth(date);
        consumer.setIntroduction(introduction);
        consumer.setLocation(location);
//        consumer.setAvator(avator);
        boolean flag = consumerService.updateConsumer(consumer);
        if (flag){
            object.put(Consts.CODE,"1");
            object.put(Consts.MSG,"修改成功");
        }else {
            object.put(Consts.CODE,0);
            object.put(Consts.MSG,"修改失败");
        }
        return object;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "deleteConsumer",method = RequestMethod.POST)
    public Object deleteConsumer(HttpServletRequest request) {
        JSONObject object = new JSONObject();
        String id = request.getParameter("id").trim();
        boolean flag = consumerService.deleteConsumer(Integer.parseInt(id));
        return flag;
    }

    /**
     * 据主键查询单个对象
     */
    @RequestMapping(value = "getConsumer",method = RequestMethod.POST)
    public Object getConsumer(HttpServletRequest request) {
        String id = request.getParameter("id");
        Consumer consumer = consumerService.getConsumer(Integer.parseInt(id));
        return consumer;
    }

    /**
     * 查询所有对象
     */
    @RequestMapping(value = "queryAllConsumer",method = RequestMethod.POST)
    public Object queryAllConsumer(HttpServletRequest request) {
//        String id = request.getParameter("id").trim();
        return consumerService.queryAllConsumer();
    }

    /**
     * 根据名字查询用户
     */
    @RequestMapping(value = "queryConsumerByName",method = RequestMethod.POST)
    public Object queryConsumerByName(HttpServletRequest request) {
        String username =request.getParameter("username").trim();
        Consumer consumer = consumerService.queryConsumerByName(username);
        return consumer;
    }


    /**
     * 更新用户头像
     *
     */
    @RequestMapping(value = "updateConsumerPic",method = RequestMethod.POST)
    public Object updateConsumerPic(@RequestParam("file")MultipartFile avatorFile,@RequestParam("id") int id){
        JSONObject jsonObject = new JSONObject();
        if (avatorFile.isEmpty()){
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"头像上传失败");
            return jsonObject;
        }
        //文件名=当前时间的毫秒+原来的文件名
        String fileName=System.currentTimeMillis()+avatorFile.getOriginalFilename();
        //文件路径
        String filePath=System.getProperty("user.dir")+System.getProperty("file.separator")+"avatorImages";
        //如果文件路径不存在，新增路径
        File file = new File(filePath);
        if (!file.exists()){
            file.mkdir();
        }
        //实际的文件地址
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        //存储到数据库里的相对文件地址
        String storeAvatorPath = "/avatorImages/"+fileName;
        try {
            avatorFile.transferTo(dest);
            Consumer consumer = new Consumer();
            consumer.setId(id);
            consumer.setAvator(storeAvatorPath);
            boolean flag = consumerService.updateConsumer(consumer);
            if (flag){
                jsonObject.put(Consts.CODE,1);
                jsonObject.put(Consts.MSG,"头像上传成功");
                jsonObject.put("avator",storeAvatorPath);
                return jsonObject;
            }else {
                jsonObject.put(Consts.CODE,0);
                jsonObject.put(Consts.MSG,"上传失败");
                return jsonObject;
            }
        } catch (IOException e) {
            jsonObject.put(Consts.CODE,0);
            jsonObject.put(Consts.MSG,"上传失败"+e.getMessage());
        }finally {
            return jsonObject;
        }
    }
}
